package com.GroupSix.tool;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordUtil {

    //密码加密功能
    public static String Md5(String str) {

        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 对字符串进行MD5加密
            byte[] hash = md.digest(str.getBytes());

            // 将字节数组转换为16进制表示的字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                // 将字节转为正整数再转换为16进制字符串
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0'); // 使输出的MD5值是32位
                }
                hexString.append(hex);
            }

            //返回加密后的密码
            return hexString.toString();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    //密码设置要求，必须包含大小写字母，数字，特殊符号

    private static final String PASSWORD_PATTERN =
            "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";//密码设置规则

    public static boolean isValidPassword(String password) {
        return password.matches(PASSWORD_PATTERN);
    }

}
